import Store from "electron-store";
import { Share } from "./share";
import { ipcMain } from "electron";
import { MsgChannel } from "@common/constants";
import { loadConfig } from "@/main/service/configLoader";
import {log} from './logManager';

const semver = require("semver");

export const initStore = (): void => {
  log.info('initStore.initStore');
  Share.localStore = new Store({
    defaults: {
        appSetting: Share.config?.appSetting
    },
  });
  log.info('store created');

  compareVersion();
  log.info('store compare version');
  ipcMain.on(MsgChannel.Store.GET, async (event, key) => {
    event.returnValue = Share.localStore.get(key);
    event.returnValue = true;
  });

  ipcMain.on(MsgChannel.Store.GET_BATCH, async (event, keys: string[]) => {
    let returnVal = {};
    keys.map((key) => {
      returnVal[key] = Share.localStore.get(key);
    });
    event.returnValue = returnVal;
  });

  ipcMain.on(MsgChannel.Store.SET, async (event, key, value) => {
    Share.localStore.set(key, value);
    event.returnValue = true;
  });

  ipcMain.on(MsgChannel.Store.DELETE, async (event, key) => {
    Share.localStore.delete(key);
    event.returnValue = true;
  });

  ipcMain.on(MsgChannel.Store.RESET, async (event, key) => {
    Share.localStore.delete(key);
    loadConfig();
    Share.localStore.set(key,Share.config?.appSetting)
    event.returnValue = true;
  });
};

const compareVersion = () => {
  const currentVersion = Share.config?.appSetting.appSettingVersion;
  const historyVersion = Share.localStore.get("appSetting.appSettingVersion");
  log.info(`Version: ${historyVersion}, current: ${currentVersion}`);
  if (!historyVersion){
    log.info('historyVersion 不存在，写入配置文件中的配置信息')
    Share.localStore.set("appSetting", Share.config?.appSetting);
  } else if (semver.eq(currentVersion, historyVersion)) {
    log.info("appSetting version没有发生变化，跳过更新appSetting的内容");
  } else if (semver.gt(currentVersion, historyVersion)) {
    log.info("appSetting的当前版本高于历史版本,更新appSetting的内容为最新");
    Share.localStore.set("appSetting", Share.config?.appSetting);
  }
};
